<script setup lang="tsx">
import { dataQuery } from "@/service/api/atmosphere/basicAnalysis";
import { airPointList } from "@/service/api/common/index";
import { type ECOption, useBoolean, useEcharts, useLoading } from "@/hooks";
import {formatNumber,dealTime} from "@/utils/tools";
import 'echarts/lib/component/dataZoom'

interface pointType {
  id: number;
  companyId: number;
  deptName: string;
  harbourName: string;
  pointCode: string;
  pointMnCode: string;
}
interface chartParamsType {
  harbouorId: number;
  pointIds: number[];
  pageNum: number;
  pageSize: number;
  beginTime: string;
  endTime: string;
}
const initPointParams = {
  pageNo: 1,
  pageSize: 10,
  harbourId: 9,
};
const initDataParams:chartParamsType = {
  harbouorId: 9,
  pointIds: [],
  pageNum:1,
  pageSize:5,
  beginTime:"2024-04-07",
  endTime:"2024-04-07",
};
const pointParams = ref({ ...initPointParams });
const pointList = ref<pointType[]>([]);
const pointTotal = ref(0);
// 点位历史数据
const historyList = ref([])
// const historyLoading = ref(true)
const hisTotal = ref(0)
const dataParams = ref({ ...initDataParams });
const hisRef = ref(null)
// 日期
const range = ref<[number, number]>([1183135260000, Date.now()])
const {
  loading: pointLoading,
  startLoading: startPoint,
  endLoading: endPoint,
} = useLoading(false);

const {
  loading: historyLoading,
  startLoading: startHis,
  endLoading: endHis,
} = useLoading(true);
const pointColumns = [
  {
    type: "selection",
    multiple: false,
  },
  {
    title: "监测点",
    align: "left",
    key: "pointCode",
  },
  {
    title: "归属企业",
    align: "center",
    key: "deptName",
  },
];
const hisColumns = [
  {
    title: "上传时间",
    align: "left",
    key: "time",
  },
  {
    title () {
      return (
        <span>
          {'TSP'}
          <br />
          {'(μg/m³)'}
        </span>
      );
      },
    align: "left",
    key: "tsp",
  },
  {
    title () {
      return (
        <span>
          {'PM₁₀'}
          <br />
          {'(μg/m³)'}
        </span>
      );
    },
    align: "left",
    key: "pm10",
  },
  {
    title () {
      return (
        <span>
          {'PM₂.₅'}
          <br />
          {'(μg/m³)'}
        </span>
      );
    },
    align: "left",
    key: "pm25",
  },
  {
    title () {
      return (
        <span>
          {'风速'}
          <br />
          {'(m/s)'}
        </span>
      );
    },
    align: "left",
    key: "ws",
  },

  {
    title () {
      return (
        <span>
          {'风向'}
          <br />
          {'(°)'}
        </span>
      );
    },
    align: "left",
    key: "wd",
  },
  {
    title () {
      return (
        <span>
          {'温度'}
          <br />
          {'(℃)'}
        </span>
      );
    },
    align: "left",
    key: "ta",
  },
  {
    title () {
      return (
        <span>
          {'湿度'}
          <br />
          {'(%)'}
        </span>
      );
    },
    align: "left",
    key: "ua",
  }
]
/** ---------------------method------------------ */
// 查询点位列表
async function getPointList() {
  startPoint();
  await airPointList(pointParams.value)
    .then((res: any) => {
      pointList.value = res.data.records;
      pointTotal.value = res.data.total;
      dataParams.value.pointIds = [Number(pointList.value[0].id)];
      getDataQuery()
    })
    .finally(() => {
      endPoint();
    });
}
// 点位查询分页
function changePointPage(page: number, size: number) {
  pointParams.value.pageNo = page;
  pointParams.value.pageSize = size;
  getDataQuery(1)
}
function changeHisPage(page: number, size: number){
  dataParams.value.pageNum = page;
  dataParams.value.pageSize = 5;
  getPointList();
}
// 选择点位(列表行)
function rowProps(e:any) {
  return {
    style: "cursor: pointer;",
    onClick: () => {
      dataParams.value.pointIds = [Number(e.id)];
      getDataQuery()
    },
  };
}
// 数据查询
async function getDataQuery(type=0) {
  startHis();
  dataQuery(dataParams.value).then((res:any)=>{
      const rows = res.record
      const x:string[] = res.x_data
      const series:any = [
        {
            name: "TSP",
            type: "line",
            data: []
          },
          {
            name: "PM₂.₅",
            type: "line",
            data: []
          },
          {
            name: "PM₁₀",
            type: "line",
            data: []
          },
      ]
      rows.forEach((item:any)=>{
        item.o3_iqi = formatNumber(item.o3_iqi,0,"");
        item.o3 = formatNumber(item.o3,0,"");
        item.pm10_iqi = formatNumber(item.pm10_iqi,0,"");
        item.pm10 = formatNumber(item.pm10,0,"");
        item.co = formatNumber(item.co,1,"");

        item.ua = formatNumber(item.ua,1,"");
        item.ta= formatNumber(item.ta,1,"");
        item.wd = formatNumber(item.wd,0,"");
        item.ws = formatNumber(item.ws,1,"");

        item.no2 = formatNumber(item.no2,0,"");
        item.tsp =formatNumber(item.tsp,0,"");
        item.pm25 = formatNumber(item.pm25,0,"");
        item.co_iqi =formatNumber(item.co_iqi,0,"");
        item.pm25_iqi =formatNumber(item.pm25_iqi,0,"");
        item.so2 = formatNumber(item.so2,0,"");
        item.no2_iqi =formatNumber(item.no2_iqi,0,"");
        item.so2_iqi =formatNumber(item.so2_iqi,0,"");
        series[0].data.push(item.tsp)
        series[1].data.push(item.pm10)
        series[2].data.push(item.pm25)
      });
      historyList.value = rows
      hisTotal.value = res.total
      if(type===0){
        renderHisCharts(x,series)
      }
  }).finally(()=>{
    endHis()
  })
}
// 渲染历史数据图表
async function renderHisCharts(x:any,series:any){
  const lineOptions = ref<ECOption>({
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "cross",
        crossStyle: {
          color: "#999"
        }
      }
    },
    toolbox: {
      feature: {
        restore: { show: true },
        magicType: { show: true, type: ["line", "bar"] },
        saveAsImage: { show: true }
      }
    },
    grid: {
      left: "3%",
      right: "3%",
      bottom: "15%",
      containLabel: true
    },
    color: [
      "#E02020",//tsp
      "#6DD400",//pm10
      "#FA6400",//pm25
      "#44D7B6",//so2
      "#32C5FF",//no2
      "#F7B500",//co
      "#0091FF",//o3
      "#190074",
      "#007454"
    ],
    legend: {
      selected:{
        TSP: true,
        "PM₂.₅": true,
        "PM₁₀": true,
      },
      data: ["TSP", "PM₁₀", "PM₂.₅"]
    },
    xAxis: [
      {
        type: "category",
        data: x,
        axisPointer: {
          type: "shadow"
        }
      }
    ],
    yAxis: [
      {
        type: "value",
        name: "污染物浓度",
        min: 0,
        splitLine: { show: false }
      },
      {
        type: "value",
        splitLine: { show: false }
      }
    ],
    dataZoom: [
      {
        type: 'slider',
        show: true,
        start: 70,
        end: 100
      },
      {
        type: "inside",
        start: 70,
        end: 100
      }
    ],
    series
  }) as Ref<ECOption>
  nextTick(async ()=>{
    const { domRef } = await useEcharts(lineOptions)
    if(hisRef.value){
      domRef.value = hisRef.value
    }
  })
}
// 默认日期
function defDate(){
  const now = new Date();
  let year = now.getFullYear(); //得到年份
  let month = now.getMonth(); //得到月份
  let date = now.getDate(); //得到日期
  month = month + 1;
  month = month.toString().padStart(2, "0");
  date = date.toString().padStart(2, "0");

  dataParams.value.beginTime = dealTime(3)
  dataParams.value.endTime = year + "-" + month + "-" + date
  range.value = [dataParams.value.beginTime, dataParams.value.endTime]
  getPointList();
}
// 选择日期
function changeDate(value: number | [number, number] | null, formattedValue: string | [string, string] | null){
  dataParams.value.beginTime = formattedValue[0]
  dataParams.value.endTime = formattedValue[1]
  getDataQuery()
}
defDate();
</script>

<template>
  <n-grid x-gap="12" :cols="4">
    <!-- 左侧图标 -->
    <n-gi :span="3">
      <n-card>
        <div class="w-350px">
          <n-date-picker v-model:formatted-value="range" type="daterange" value-format="yyyy-MM-dd" time-picker-format="yyyy-MM-dd" @confirm="changeDate"/>
        </div>
        <n-tabs
          class="card-tabs"
          default-value="dataQ"
          size="large"
          animated
          pane-wrapper-style="margin: 0 -4px"
          pane-style="padding-left: 4px; padding-right: 4px; box-sizing: border-box;"
        >
          <n-tab-pane name="dataQ" tab="数据查询">
            <div ref="hisRef" class="h-300px" />
            <n-data-table
              :columns="hisColumns"
              :data="historyList"
              :loading="historyLoading"
            />
            <n-flex justify="center" :style="{ marginTop: '5px' }">
              <Pagination
                :count="hisTotal"
                @change="changeHisPage"
                v-if="hisTotal > dataParams.pageSize"
                :page="dataParams.pageNum"
                :pageSize="dataParams.pageSize"
              />
            </n-flex>
          </n-tab-pane>
          <n-tab-pane name="dataM" tab="气象数据"> 2 </n-tab-pane>
          
        </n-tabs>
      </n-card>
    </n-gi>
    <!-- 右侧点位列表 -->
    <n-gi>
      <n-card>
        <n-data-table
          v-model:checked-row-keys="dataParams.pointIds"
          :columns="pointColumns"
          :data="pointList"
          :loading="pointLoading"
          :row-key="(row) => row.id"
          :row-props="rowProps"
        />
        <n-flex justify="center" :style="{ marginTop: '5px' }">
          <Pagination
            :count="pointTotal"
            @change="changePointPage"
            v-if="pointTotal > pointParams.pageSize"
            :page="pointParams.pageNo"
            :pageSize="pointParams.pageSize"
          />
        </n-flex>
      </n-card>
    </n-gi>
  </n-grid>
</template>

<style lang="scss" scoped>
::v-deep .n-tabs-nav-scroll-content {
  min-width: 80%;
}
</style>
